<h1><?php echo $this->pageTitle; ?></h1>
<?php echo $ajax->form('CRH', 'post', array('update'=>'content', 'indicator' => 'indicator', 'url'=>array('action'=>'save')));?>
<div class="toolbar">
    <div id="tLeft">
        <?php if ($mode == 'add') : ?>
            <?php echo $this->element('toolbar', array('buttons' => array('save', 'clear', 'back'))); ?>
        <?php else : // mode edit ?>
            <?php echo $this->element('toolbar', array('buttons' => array('add', 'save', array('print' => array('model' => 'CRH')), 'back'))); ?>
        <?php endif; ?>
    </div>
    <div id="tRight"><?php echo $this->element('neighbors', array('model' => 'CRH', 'title' => 'return_no')); ?></div>
</div>

<?php echo $form->input('CRH.id'); ?>
<?php echo $form->hidden('mode', array('value' => $mode)); ?>

<fieldset>
    <table>
        <tr>
            <td width="200px"><?php echo $form->label('CRH.return_date', 'Return date'); ?></td>
            <td width="250px">
                <?php if($mode == 'add') : ?>
                    <?php echo $html->tag('span', $today); ?>
                    <?php echo $form->hidden('CRH.return_date', array('id' => 'return_date', 'value' => $today)); ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['CRH']['return_date']); ?>
                <?php endif; ?>
            </td>
            <td width="150px"><?php echo $form->label('CRH.cust_return_status_id', 'Status'); ?></td>
            <td>
                <?php if ($mode == 'edit') : ?>
                    <?php echo $html->tag('span', $this->data['CRS']['title']); ?>
                <?php else : ?>
                    <?php echo $returnStatus; ?>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('CRH.return_no', 'Return no'); ?></td>
            <td>
                <?php if($mode == 'add') : ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['CRH']['return_no']); ?>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('CRH.return_by', 'Return by'); ?></td>
            <td>
                <?php if($mode == 'add') : ?>
                    <?php echo $html->tag('span', $return_by); ?>
                    <?php echo $form->hidden('CRH.return_by', array('value' => $return_by)); ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['CRH']['return_by']); ?>
                <?php endif; ?>
            </td>
            <?php if ($mode == 'edit' && $this->data['CRH']['cust_return_status_id'] != CRS::RETURNING) : ?>
            <td><?php echo $form->label('CRH.vendor_document_no', 'Vendor Document no.'); ?></td>
            <td>
                    <?php echo !empty($this->data['CRH']['vendor_document_no'])? $this->data['CRH']['vendor_document_no']: '-' ?>
            </td>
            <?php endif; ?>
        </tr>
    </table>
</fieldset>

<fieldset>
    <table class="data">
        <thead>
            <tr>
                <th width="35px">No</th>
                <th width="130px">Part no.</th>
                <th width="120px">Stock code</th>
                <th>Description</th>
                <th width="100px">Return Qty</th>
                <th width="50px">Unit</th>
                <th width="60px">Index</th>
                <?php if($mode == 'add') : ?>
                <th class="action">&nbsp;</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody id="productRow">
            <?php if ($mode == 'add') : ?>
            <?php else : $count = count($this->data['CR'])// mode edit ?>
        <tbody class="edit">
                <?php for($i = 0; $i < $count; ++$i) : ?>
            <tr class="<?php echo (($i + 1) % 2 == 0)? 'even-cell' : 'odd-cell'; ?>">
                <td><span><?php echo $i + 1; ?></span></td>
                <td>
                            <?php echo $html->link($this->data['CR'][$i]['Product']['part_no'],
                            '/cust_product_sites/view/' . $this->data['CR'][$i]['cust_product_site_id'] . '/' . strtotime('now'),
                            array('target' => '_blank')); ?>
                </td>
                <td class="center"><?php echo $this->data['CR'][$i]['CustProductSite']['stock_code']; ?></td>
                <td>
                            <?php echo !empty($this->data['CR'][$i]['CustProductSite']['text'])?
                            $this->data['CR'][$i]['CustProductSite']['text']:
                            $this->data['CR'][$i]['Product']['text']; ?>
                </td>
                <td class="text-right"><?php echo $this->data['CR'][$i]['return_qty']; ?></td>
                <td class="center">
                            <?php echo $this->data['CR'][$i]['Product']['Unit']['title']; ?>
                </td>
                <td class="center">
                            <?php echo $ajax->link($html->image('icon/popup.png', array('alt' => 'Index information')),
                            array('controller' => 'products_serials', 'action' => 'popup_cust_view', $this->data['CR'][$i]['cust_product_site_id'] . '/' . 'cust_stock_out_id:' . $this->data['CR'][$i]['id'] . '/cust_stock_out_type:' . CR::CUST_STOCK_OUT_TYPE),
                            array('update' => 'content', 'position' => 'bottom', 'indicator' => 'indicator' ), null, false); ?>
                </td>
            </tr>
                <?php endfor; ?>
            <?php endif; ?>
        </tbody>
    </table>
</fieldset>
<fieldset>
    <table>
        <tr>
            <td width="50px" class="top"><?php echo $form->label('CRH.remark'); ?></td>
            <td><?php echo $form->textarea('CRH.remark', array('cols' => 80, 'rows' => 3)); ?></td>
        </tr>
    </table>
</fieldset>

<?php echo $form->end(); ?>
<?php if ($mode == 'add') : ?>

<script type="text/javascript">
    // JSON เก็บ part no ที่ป้อนเข้ามา อ้างไปยังลำดับแถว
    var partNos = {};

    requestCR = function(event) {
        var element = Event.element(event);
        var part_no = $j.trim($F(element));
        var no = element.readAttribute("no");   // ลำดับแถวปัจจุบัน เริ่มที่ 0

        if(part_no == "") {
            //alert("No part no");
            return;
        }

        // ถ้ายังไม่มี part no นี้อยู่
        if (partNos[part_no] == null) {
            var url = base + "/cust_returns/json_find_by_part_no/";
            var params = {part_no: part_no};
            postRequest(url, params, function(data) {
                // พบข้อมูล
                if (data != false) {
                    if (data.CustProductSite.dispatch_from != ITS_PREFIX) {
                        element.clear();
                        alert("This product is not dispatch from ITS.");
                        return;

                    } else if (data.CustProductSite.current_stock == 0) {
                        element.clear();
                        alert("This product is out of stock.");
                        return;
                    }
                } else { // ไม่พบข้อมูล (กรอกข้อมูลผิด...)
                    element.clear();
                    alert("No product found.");
                    return;
                }

                $("CR" + no + "PartNo").hide();
                $("CR" + no + "PartNoSpan").update(data.Product.part_no);
                $("CR" + no + "PartNoSpan").show();
                $("CR" + no + "StockCode").update(data.CustProductSite.stock_code);
                $("CR" + no + "CustProductSiteId").value = data.CustProductSite.id;
                $("CR" + no + "ProductText").update(data.CustProductSite.text != null? data.CustProductSite.text: data.Product.text);
                $("CR" + no + "ProductId").value = data.CustProductSite.product_id;
                $("CR" + no + "CurrentStock").update("/" + data.CustProductSite.current_stock);
                $("CR" + no + "ProductUnitTitle").update(data.Product.Unit.title);
                $("CR" + no + "ReturnQty").value = 1;

                // ดักจับ Event กดลบแถว.
                $j('#linkCR' + no + 'Delete').bind('click', function() {
                    // ลบรายการ part no ออกจาก list
                    var p = $j("#CR" + no + "PartNoSpan").text();
                    var sc = $j("#CR" + no + "StockCode").text();
                    partNos[p] = undefined;
                    partNos[sc] = undefined;

                    // ลบ แถว
                    $j('#CR' + no + 'Index').parents('tr').remove();

                    // จัดลำดับตัวเลขหน้าแถวใหม่
                    $j('#productRow').runno();
                }).show();

                partNos[data.Product.part_no] = no;
                partNos[data.CustProductSite.stock_code] = no;

                var nextRow = (parseInt(no) + 1);
                createRow(nextRow)
                $("CR" + nextRow + "PartNo").focus();
                requestProductSerial(no);
            }
        );
        } else {
            element.clear();
            var row = partNos[part_no]; // แถวที่มี part_no นี้อยู่
            $("CR" + row + "ReturnQty").value = parseInt($("CR" + row + "ReturnQty").value) + 1;
            setTimeout(function() {
                $("CR" + no + "PartNo").focus();
            }, 100);
            checkReturnQty(row);
        }
    }

    requestProductSerial = function(no) {
        var url = base + "/cust_returns/json_find_product_serials_by_cust_product_site_id/";
        var params = {
            cust_product_site_id: $F("CR" + no + "CustProductSiteId")
        };
        postRequest(url, params, function(data) {
            createSerialElement(data, no);
            checkReturnQty(no);
        });
    };

    checkReturnQty = function(no) {
        var currentStockQty = parseInt($("CR" + no + "CurrentStock").innerHTML.substring(1)) // innerHTML = "/[CurrentStock]"
        var returnQty = parseInt($F("CR" + no + "ReturnQty"))
        if (returnQty > currentStockQty) {
            alert("Please return quantity less than current stock quantity")
            $("CR" + no + "ReturnQty").value = currentStockQty;
            returnQty = currentStockQty;
        }
        // select จำนวน ProductSerial ที่จะ return ใหม่ตามจำนวน returnQty
        $j("#Index" + no + " :checkbox").attr('checked', false);
        var stocksIn = $j("#Index" + no + " :checkbox").attr('checked', false).slice(0, returnQty);
        // ถ้าเป็น IE 6 ต้องใช้ defaultChecked เพิ่มถึงจะ ติ๊กถูกให้จริง ๆ
        if ($j.browser.msie && ($j.browser.version == 6)) {
            stocksIn.attr('defaultChecked', true);
        } else {
            stocksIn.attr('checked', true);
        }
        $j('table.data tr:not(:has(:checked))').removeClass('selected');
        $j('table.index tr:has(:checked)').addClass('selected');
    }

    /**
     * สร้าง Popup ที่มีข้อมูล ProductSerial
     */
    function createSerialElement(data, row) {
        var divIndex = $("Index" + row)
        var runno = 1;
        var index = 0;
        $j("#popupIndex" + row).dialog("option", "title", "Select Product serial to return.");
        var table = new Element('table', {'class': 'data index', 'id': 'table' + row});
        var thead = new Element('thead');
        var tr = new Element('tr');
        tr.update(new Element('th', {width: 35}).update('No.'));
        tr.insert(new Element('th', {width: 120}).update('Location'));
        tr.insert(new Element('th', {width: 120}).update('Serial no.'));
        tr.insert(new Element('th').update('Other Information'));
        tr.insert(new Element('th', {width: 80}).update('Return'));
        thead.update(tr);
        table.insert(thead);
        var tbody = new Element('tbody');
        table.insert(tbody);
        divIndex.insert(table);
        $R(0, data.length, true).each(function() {
            var tr = new Element('tr');
            var tdNo = new Element('td', {'class': 'center'});
            tdNo.update(runno);
            tdNo.insert('<input type="hidden" id="Product' + row + 'Serial' + index + 'Id" name="data[CR][' + row + '][ProductSerial][' + index + '][id]" value="' + data[index].ProductSerial.id + '" />');
            tr.insert(tdNo);

            var tdLocation = new Element('td', {'id': 'Product' + row + 'Serial' + index + 'CustLocationTd'});
            tdLocation.insert(data[index].CustLocation.name);
            tr.insert(tdLocation);

            var tdSerial = new Element('td');
            tdSerial.update('<div>' + (data[index].ProductSerial.serial_no != null? data[index].ProductSerial.serial_no: 'N/A') + '</div>');
            tr.insert(tdSerial);

            var tdOtherIn = new Element('td');
            tdOtherIn.update('<div>' + (data[index].ProductSerial.other_information != null? data[index].ProductSerial.other_information: 'N/A') + '</div>');
            tr.insert(tdOtherIn);

            // คอลัมภ์นี้ใช้บอกว่า ProductSerial นี้ถูก stock in ด้วยหรือไม่
            var tdReturn = new Element('td', {'class': 'center'});
            tdReturn.update('<input type="checkbox" id="Product' + row + 'Serial' + index + 'Return" name="data[CR][' + row + '][ProductSerial][' + index + '][return]" value="1" />');
            tr.insert(tdReturn);

            tbody.insert(tr);

            // ดักจับ event การติ๊ก Stock in เปลี่ยน stock_in_qty ตามจำนวนที่ติ๊ก
            $j('#Product' + row + 'Serial' + index + 'Return').bind("click change", function() {
                $j("#CR" + row + "ReturnQty").val($j("#Index" + row + " :checkbox:checked").length);
                $j('table.data tr:not(:has(:checked))').removeClass('selected');
                $j('table.index tr:has(:checked)').addClass('selected');
            });

            // ดักจับ event ให้คลิกที่ตารางแล้วไปคลิกที่ checkbox ด้วย
            $j(tr).handover();
            $j(tr).bind('click', function(event) {
                var tagName = event.target.tagName.toLowerCase();
                if (tagName != 'input' && tagName != 'select' && tagName != 'option') {
                    var checkbox = $j(':checkbox', this);
                    checkbox.attr('checked', !checkbox.attr('checked'));
                    checkbox.change();
                }
            });
            runno++; index++;
        });
    }

    function createRow(row) {
        var tBody = $("productRow");
        var tr = new Element("tr");
        tr.addClassName(((row + 1) % 2 == 0)? "even-cell" : "odd-cell");

        tr.update('<input id="CR' + row + 'Id" type="hidden" value="" name="data[CR][' + row + '][id]" />');

        var tdNo = new Element("td");
        tdNo.update('&nbsp;');
        tr.insert(tdNo);

        var tdPartNo = new Element("td");
        tdPartNo.insert('<input id="CR' + row + 'PartNo" type="text" value="" no="' + row + '" name="data[CR][' + row + '][part_no]"/>');
        tdPartNo.insert('<input id="CR' + row + 'ProductId" type="hidden" value="" name="data[CR][' + row + '][product_id]"/>');
        tdPartNo.insert('<input id="CR' + row + 'CustProductSiteId" type="hidden" value="" name="data[CR][' + row + '][cust_product_site_id]"/>');
        tdPartNo.insert('<span id="CR' + row + 'PartNoSpan" style="display: none"></span>');
        tr.insert(tdPartNo);

        var tdStockCode = new Element("td", {'class': 'center'});
        tdStockCode.insert('<span id="CR' + row + 'StockCode"></span>');
        tr.insert(tdStockCode);

        var tdTitle = new Element("td");
        tdTitle.insert('<span id="CR' + row + 'ProductText"></span>');
        tr.insert(tdTitle);

        var tdReturnQty = new Element("td");
        var div = new Element("div", {'class': 'inline'});
        div.update('<input id="CR' + row + 'ReturnQty" no="' + row + '" class="text-right" type="text" value="" maxlength="3" size="3" name="data[CR][' + row + '][return_qty]"/>');
        tdReturnQty.insert(div);
        tdReturnQty.insert('<span id="CR' + row + 'CurrentStock"></span>');
        tr.insert(tdReturnQty);

        var tdUnit = new Element("td", {'class': 'center'});
        tdUnit.insert('<span id="CR' + row + 'ProductUnitTitle"></span>');
        tr.insert(tdUnit);

        var tdIndex = new Element("td", {id: 'tdIndex' + row, "class": "center"});
        tdIndex.insert('<a href="#" id="CR' + row + 'Index"><?php echo $html->image('icon/popup.png', array('title' => 'Index', 'alt' => 'Index')); ?><div id="Index' + row + '" style="display: none;"></div><div id="popupIndex' + row + '"></div>');
        tr.insert(tdIndex);

        var tdDelete = new Element("td", {"class": "center"});
        tdDelete.insert('<a href="#" id="linkCR' + row + 'Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a>');
        tr.insert(tdDelete);

        tBody.insert(tr);
        $j('#productRow').runno();
        addRowListener(row);
    }

    function addRowListener(row) {
        $("CR" + row + "PartNo").observe('keypress', partNoKeyPress);

        $("CR" + row + "PartNo").observe('blur', function(event) {
            requestCR(event);
        });

        $("CR" + row + "ReturnQty").observe('keypress', stopKeyEnter);
        $("CR" + row + "ReturnQty").observe('change', function(event) {
            checkReturnQty(Event.element(event).readAttribute("no"));
        });

        $("CR" + row + "Index").observe('click', function(event) {
            popupIndex(row);
        });
        initPopUpIndex(row);
    }
    $j(function() {
        createRow(0);

        $j('#CRHId').parent('form').beforeSubmit(function() {
            if (!$j.validateField('CR0PartNo', 'Product', 'CR0PartNo')) {
                return false;
            }

            if (!$j.validateColumns('ReturnQty', 'Return Qty', {callback: $j.QTY})) {
                return false;
            }
            return true;
        });
    })

</script>
<?php endif; ?>
<?php //echo $ajax->link('Send email', 'sendEmail/' . $this->data['CRH']['id'], array('indicator' => 'indicator', 'update' => 'content')); ?>
<?php //debug($this->data);